﻿using Beryl.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace Beryl.Model
{
    //生产报工
    public class ProductionReport
    {
        private static ProductionReport instance = null;
        private static readonly object uniqueLock = new object();

        public static ProductionReport Instance
        {
            get
            {
                lock (uniqueLock)
                {
                    if (instance == null)
                    {
                        instance = new ProductionReport();
                    }
                }
                return instance;
            }
        }
        public ProductionReport() { }

        //流传单查询
        public List<string> getBarCode(string para,string data)
        {
            List<string> list = new List<string>();
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            try
            {
                string sql = string.Format(@"select cMOLotNo,CAST(QcResult AS VARCHAR) AS QcResult,CAST(dLotQty AS VARCHAR) AS dLotQty,a.cProductDepNo,cStatusNo,a.cMatNo,cOrderNo,cLotType,b.cSpecifucation from APS_ProLotOrder a join [dbo].[APS_MatData_V] b on a.cMatNo = b.cMatNo where a.cBarCode = '{0}'", para);
                string strPicYZ1 = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql));
                if (!strPicYZ1.Equals("[]"))
                {
                    Newtonsoft.Json.Linq.JArray jsonArr = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(strPicYZ1);
                    var k = jsonArr[0];
                    int status = int.Parse(k["cStatusNo"].ToString());
                    if(status < 91)
                    {
                        if (int.Parse(k["QcResult"].ToString()) <= 3)
                        {
                            list.Add("质检结果异常!");
                        }else
                        {
                            list.Add(strPicYZ1);
                        }
                    }else
                    {
                        list.Add("批次已关闭，无需报工!");
                    }
                }
                else
                {
                    list.Add("请检查流传单!");
                }
            }
            catch(Exception e)
            {
                //CommonMethod.Instance.InsertLog(name, e.Message, CommonMethod.LogType.Error, data,"生产报工获取流传单信息失败：" + para);
                CommonMethod.Instance.InsertLog1(para, e.Message, data, CommonMethod.LogType.Error, name, "", true);
                list.Add(e.Message);
                return list;
            }
            //CommonMethod.Instance.InsertLog(name, list[0], CommonMethod.LogType.Info, data,"生产报工获取流传单信息：" + para);
            CommonMethod.Instance.InsertLog1(para, list[0], data, CommonMethod.LogType.Info, name, "", true);
            return list;
        }

        public List<string> getQueryData(string para, string data)
        {
            string lastGX = "";
            List<string> list = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            Newtonsoft.Json.Linq.JArray jsonArr = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(para);
            var k = jsonArr[0];
            try
            {
                string sql = string.Format(@"select a.cOperationName,a.cOperationNo,a.cOpSeq from APS_ValidRouting a inner join APS_Operation_V b on a.cOperationNo = b.cOperationNo where b.cReportFlag = 1 and a.cOrderNo ='{0}' order by a.cOpSeq;", k["cMOLotNo"].ToString());
                string strPicYZ1 = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql));
                string GX;
                if (strPicYZ1.Equals("[]"))
                {
                    //dic.Add("工序", "工序查询失败,请检查");
                    throw new Exception("工序查询失败!");
                }
                else
                {
                    GX = strPicYZ1;
                    dic.Add("工序", strPicYZ1);
                }
                //string sql1 = string.Format(@"select cOperationNo,cOperationName from APS_ValidRouting where cMatNo='{0}' and cOrderNo ='{1}' and ReportTime is not null order by cOpSeq desc", k["cMatNo"].ToString(), k["cMOLotNo"].ToString());
                //strPicYZ1 = JsonConvert.SerializeObject(CheckData.Instance.selectDatabase(sql1));//转为json
                //if(strPicYZ1.Equals("[]"))
                //{
                //    dic.Add("最后工序", "最后工序查询失败");
                //}else
                //{
                //取第一行
                //Newtonsoft.Json.Linq.JArray jsonArr1 = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(strPicYZ1);
                //var kk = jsonArr1[0];
                //strPicYZ1 = kk.ToString();
                //strPicYZ1 = CheckData.Instance.JosnChange(strPicYZ1);
                //lastGX = strPicYZ1;
                //dic.Add("最后工序", strPicYZ1);
                // }
                string sql2 = string.Format(@"select PEquipment,Operator,cProcess,cProcessCode,cProStartTime from APS_PhistoryTable where cMOLotNo = '{0}' and cProEndTime is null", k["cMOLotNo"].ToString());
                strPicYZ1 = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql2));//转为json
                if(strPicYZ1.Equals("[]"))
                {
                    dic.Add("已开工", "查询已报工失败是否继续?");
                }else
                {
                    //string result = CheckData.Instance.CheckPRData(strPicYZ1);//更新时间数据
                    //if (!result.Contains("["))
                    //{
                    //    dic.Add("已开工", strPicYZ1);
                    //    throw new Exception(result);
                    //}
                    //else
                    //{
                    //    dic.Add("已开工", result);
                    //}
                    Newtonsoft.Json.Linq.JArray jsonArr1 = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(strPicYZ1);
                    if(jsonArr1.Count > 1)
                    {
                        Newtonsoft.Json.Linq.JArray jsonArrGX = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(GX);
                        int lengthGX = jsonArr1.Count;
                        int j = 0;
                        for(int i = 0; i< jsonArr1.Count;i++)
                        {
                            for(int p = 0; p < jsonArrGX.Count;p++)
                            {
                                string gxcode = jsonArrGX[p]["cOperationNo"].ToString();
                                string gxcode1 = jsonArr1[i]["cProcessCode"].ToString();
                                if (gxcode.Equals(gxcode1))
                                {
                                    j++;
                                }
                            }
                        }
                        if(!(lengthGX == j))
                        {
                            throw new Exception("已开工工序不存在流传单中");
                        }
                       jsonArr1.RemoveAt(0);
                    }
                    string ret = JsonConvert.SerializeObject(jsonArr1);
                    string result = CommonMethod.Instance.CheckPRData(ret);//更新时间数据
                    if (!result.Contains("["))
                    {
                        dic.Add("已开工", ret);
                    }
                    else
                    {
                        dic.Add("已开工", result);
                    }
                    var k1 = jsonArr1[0];
                    string sql3 = string.Format(@"select * from Sys_PsnNum where cPsn_Num = '{0}'", k1["Operator"].ToString());
                    strPicYZ1 = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql3));//转为json
                    if (strPicYZ1.Equals("[]"))
                    {
                        dic.Add("员工", "员工查询失败");
                    }
                    else
                    {
                        dic.Add("员工", strPicYZ1);
                    }
                    string LLnum = CommonMethod.Instance.getLLNum(k1["cProcess"].ToString(), k["cMOLotNo"].ToString(), GX, lastGX, k["dLotQty"].ToString());
                    if (LLnum.Contains("error"))
                    {
                        dic.Add("来料数", "0");
                    }
                    else
                    {
                        dic.Add("来料数", LLnum);
                    }
                }
                string jsonStr = JsonConvert.SerializeObject(dic);
                jsonStr = "[" + jsonStr + "]";
                list.Add(jsonStr);
            }
            catch(Exception e)
            {
                // CommonMethod.Instance.InsertLog(name, e.Message, CommonMethod.LogType.Error, data, "生产报工获取订单号信息失败：" + para);
                CommonMethod.Instance.InsertLog1(k["cMOLotNo"].ToString(), e.Message, data, CommonMethod.LogType.Error, name, "", true);
                list.Add(e.Message);
                return list;
            }
            CommonMethod.Instance.InsertLog1(k["cMOLotNo"].ToString(), list[0], data, CommonMethod.LogType.Info, name, "", true);
            return list;
        }

        //取消使用20230921
        public List<string> CheckPRData(string para, string data)
        {
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            List<string> list = new List<string>();
            try
            {
                string json = CommonMethod.Instance.CheckPRSummitData(para);
                list.Add(json);
            }
            catch(Exception e)
            {
                LogUtil.Error(name + e.Message);
                list.Add(e.Message);
                return list;
            }
            LogUtil.Log(name + list[0]);
            return list;
        }

        //根据时间获取班次
        //20:00为白班 20:01为夜班，08:00为夜班 08:01为白班
        public List<string> getTimeBC(string para, string data)
        {
            List<string> list = new List<string>();
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            try
            {
                string endTime = para.Insert(2, ":");
                DateTime dd = Convert.ToDateTime("00:00");
                DateTime dd1 = Convert.ToDateTime("08:00");
                DateTime ddd = Convert.ToDateTime("20:00");
                DateTime ddd1 = Convert.ToDateTime("23:59");
                DateTime dddd = Convert.ToDateTime("08:00");
                DateTime dddd1 = Convert.ToDateTime("20:00");
                string bc = "";
                DateTime endTime1 = Convert.ToDateTime(endTime);
                if ((DateTime.Compare(endTime1, dd) >= 0 && DateTime.Compare(endTime1, dd1) <= 0) || (DateTime.Compare(endTime1, ddd) > 0 && DateTime.Compare(endTime1, ddd1) <= 0))//夜班  
                {
                    bc = "[夜]";
                    list.Add(bc);
                }
                if (DateTime.Compare(endTime1, dddd) > 0 && DateTime.Compare(endTime1, dddd1) <= 0)//白班
                {
                    bc = "[白]";
                    list.Add(bc);
                }
            }
            catch(Exception e)
            {
                //CommonMethod.Instance.InsertLog(name, e.Message, CommonMethod.LogType.Error, data,"生产报工根据时间获取班次信息失败，输入时间为：" + para);
                CommonMethod.Instance.InsertLog1("", e.Message, data, CommonMethod.LogType.Error, name, "", true);
                list.Add(e.Message);
                return list;
            }
            //CommonMethod.Instance.InsertLog(name, list[0], CommonMethod.LogType.Info, data, "生产报工根据时间获取班次信息，输入时间为：" + para);
            CommonMethod.Instance.InsertLog1("", "生产报工根据时间获取班次信息，输入时间为：" + para + list[0], data, CommonMethod.LogType.Info, name, "", true);
            return list;
        }


        //提交处理
        public List<string> SummitDual(string para, string data)
        {
            List<string> list = new List<string>();
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            //string sql = string.Format(@"insert into APS_ExceptionRecord (cMOLotNo,PEquipment,AType,AClassification,EDescription,CreatePerson,CreateTime,cProcess) values");
            Newtonsoft.Json.Linq.JArray jsonArr = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(para);
            // string dates = DateTime.Now.ToString().Replace('-', '/');
            var k = jsonArr[0];
            try
            {
                string gxCode = "";
                string sqlcode = string.Format(@"SELECT * FROM [192.168.1.5].UFDATA_168_2013.dbo.sfc_operation where Description = '{0}'", k["当前工序"].ToString());
                var k1 = CommonMethod.Instance.selectDatabase(sqlcode);   
                var KnRow = k1.Select($"Description = '{k["当前工序"].ToString()}'");
                if (KnRow.Length > 0)
                {
                    var Kn1 = KnRow[0];
                    gxCode = Kn1["OperationId"].ToString();
                }
                else
                {
                    throw new Exception("查询工序code失败.");
                }

                //string AType = "生产管理";
                //string AClassification = "报工异常";
                //string EDescription1 = "报工数量超上限";
                //string EDescription2 = "上工序未报工";
                //switch (tag)
                //{
                //    case 1:
                //        sql += "('" + k["生产批次号"].ToString() + "','" + k["设备"].ToString() +
                //           "','" + AType + "','" + AClassification + "','" + EDescription1 +
                //           "','" + k["员工Num"].ToString() + "','" + dates + "','" + k["当前工序"].ToString() + "');";
                //        break;
                //    case 2:
                //        sql += "('" + k["生产批次号"].ToString() + "','" + k["设备"].ToString() +
                //           "','" + AType + "','" + AClassification + "','" + EDescription2 +
                //           "','" + k["员工Num"].ToString() + "','" + dates + "','" + k["当前工序"].ToString() + "');";
                //        break;
                //    case 3:
                //        sql += "('" + k["生产批次号"].ToString() + "','" + k["设备"].ToString() +
                //         "','" + AType + "','" + AClassification + "','" + EDescription1 +
                //         "','" + k["员工Num"].ToString() + "','" + dates + "','" + k["当前工序"].ToString() + "'),('" + k["生产批次号"].ToString() + "','" + k["设备"].ToString() +
                //           "','" + AType + "','" + AClassification + "','" + EDescription2 +
                //           "','" + k["员工Num"].ToString() + "','" + dates + "','" + k["当前工序"].ToString() + "');";
                //        break;
                //}

                SqlHelper.IniConnString();
                var connstr = SqlHelper.GetConnSting();

                //DataTable dt = new DataTable();
                //dt.Columns.Add("cOrderNo", typeof(String));
                //dt.Columns.Add("cOperationNo", typeof(String));
                //dt.Columns.Add("TotalNum", typeof(String));

                //DataRow dr;
                //dr = dt.NewRow();
                //dr["cOrderNo"] = k["生产批次号"].ToString();
                //dr["cOperationNo"] = k["当前工序No"].ToString();
                //dr["TotalNum"] = k["订单数量"].ToString();

                //SqlHelper.ExecuteNonQueryTypedParams(connstr, "PS_BGCHECK", dr); //checkTotal 为存储过程名称


                //检查是否超过量 查看存储过程返回
                char isReturnReport = '0';
                if (k["返工报工"].ToString().Contains("是"))
                {
                    isReturnReport = '1';
                }

                SqlConnection conn = new SqlConnection(connstr);
                 conn.Open();
                 SqlCommand cmd = new SqlCommand("PS_BGCHECK", conn);
                 cmd.CommandType = CommandType.StoredProcedure;
                 cmd.Parameters.Add(new SqlParameter("@cOrderNo", SqlDbType.NVarChar));
                 cmd.Parameters.Add(new SqlParameter("@cOperationNo", SqlDbType.NVarChar));
                 cmd.Parameters.Add(new SqlParameter("@TotalNum", SqlDbType.Float));
                 cmd.Parameters["@cOrderNo"].Value = k["生产批次号"].ToString();
                 cmd.Parameters["@cOperationNo"].Value = gxCode;
                 cmd.Parameters["@TotalNum"].Value = k["良品数"].ToString();
                 cmd.Parameters.Add(new SqlParameter("@return", SqlDbType.Int));
                 cmd.Parameters["@return"].Direction = ParameterDirection.ReturnValue;
                 cmd.ExecuteNonQuery();
                 conn.Close();
                string reslut = cmd.Parameters["@return"].Value.ToString();
                if(reslut.Contains("1") && isReturnReport == 0)
                {
                    throw new Exception("数量已超出流传单数量,提交失败:"+ "生产批次号:" + k["生产批次号"].ToString()+ ",良品数:" + k["良品数"].ToString() + ",工序号:" + gxCode);
                }

                string startTime = k["开始时间"].ToString();
                if (!k["开始时间"].ToString().Contains(":"))
                {
                    startTime = startTime.Insert(2, ":");
                }
                string cProStartTime = k["开始日期"].ToString() + " " + startTime;
                string cProEndTime = k["结束日期"].ToString() + " " + k["结束时间"].ToString();


                bool timeOK = CommonMethod.Instance.DataLineOut(cProStartTime, cProEndTime);
                if (!timeOK)//开始时间不能大于结束时间
                {
                    throw new Exception("开始时间大于结束时间:" + "生产批次号:" + k["生产批次号"].ToString() + ",良品数:" + k["良品数"].ToString() + ",工序号:" + gxCode);
                }
               
                if(!(gxCode.Equals("1000000007") || gxCode.Equals("1000000039") || gxCode.Equals("1000000032")))
                {
                    bool time_Interval = CommonMethod.Instance.timeInterval(cProStartTime, cProEndTime);
                    if (!time_Interval)//开始时间与结束时间少于10分钟
                    {
                        throw new Exception("开始时间与结束时间少于10分钟,请检查:" + "生产批次号:" + k["生产批次号"].ToString() + "，良品数:" + k["良品数"].ToString() + ",工序号:" + gxCode);
                    }
                }
                
                DataTable dt1 = new DataTable();
                dt1.Columns.Add("cMOLotNo", typeof(string));
                dt1.Columns.Add("PEquipment", typeof(string));
                dt1.Columns.Add("Operator", typeof(string));
                dt1.Columns.Add("IMaterialsNum", typeof(decimal));
                dt1.Columns.Add("cProcess", typeof(string));
                dt1.Columns.Add("MaterialCode", typeof(string));
                dt1.Columns.Add("Shift", typeof(string));
                dt1.Columns.Add("GNumber", typeof(int));
                dt1.Columns.Add("ANumber", typeof(int));
                dt1.Columns.Add("startTime", typeof(DateTime));
                dt1.Columns.Add("endTime", typeof(DateTime));
                dt1.Columns.Add("cProcessCode", typeof(string));
                dt1.Columns.Add("isReturnReport", typeof(char));
                dt1.Columns.Add("orderNostr", typeof(string));
                dt1.Columns.Add("Specification", typeof(string));

              
                string shiftName = "白班";
                if (k["班次"].ToString().Contains("夜"))
                {
                    shiftName = "夜班";
                }
               
                decimal IMaterialsNum = Convert.ToDecimal(k["来料数"].ToString()) == 0 ? Convert.ToDecimal(k["良品数"].ToString()) : Convert.ToDecimal(k["来料数"].ToString());
                DataRow dr1;
                dr1 = dt1.NewRow();
                dr1["cMOLotNo"] = k["生产批次号"].ToString();
                dr1["PEquipment"] = k["设备"].ToString();
                dr1["Operator"] = k["员工Num"].ToString();
                dr1["IMaterialsNum"] = Convert.ToDecimal(k["良品数"].ToString());
                dr1["cProcess"] = k["当前工序"].ToString();
                dr1["MaterialCode"] = k["物料编码"].ToString();
                dr1["Shift"] = shiftName;
                dr1["GNumber"] = int.Parse(k["良品数"].ToString());
                dr1["ANumber"] = int.Parse(k["不良数"].ToString());
                dr1["startTime"] = DateTime.Parse(cProStartTime);
                dr1["endTime"] = DateTime.Parse(cProEndTime);
                dr1["cProcessCode"] = gxCode;
                dr1["isReturnReport"] = isReturnReport;
                dr1["orderNostr"] = k["生产订单号"].ToString();
                dr1["Specification"] = k["物料规格"].ToString();
                SqlHelper.ExecuteNonQueryTypedParams(connstr, "PM_OrderEnd", dr1); //checkTotal 为存储过程名称
            }
            catch(Exception e)
            {
                list.Add(e.Message);
                //CommonMethod.Instance.InsertLog(name, e.Message, CommonMethod.LogType.Error, data,"生产报工提交失败");
                CommonMethod.Instance.InsertLog1(k["生产批次号"].ToString(), k["当前工序"].ToString() + e.Message, data, CommonMethod.LogType.Error, name, "", true);
                return list;
            }
            list.Add("[0]");
            //CommonMethod.Instance.InsertLog(name, list[0], CommonMethod.LogType.Info, data,"生产报工提交成功:" + para);
            CommonMethod.Instance.InsertLog1(k["生产批次号"].ToString(), k["当前工序"].ToString() + "生产报工提交成功", data, CommonMethod.LogType.Info, name, "", true);
            return list;
        }


        //不良品处理
        public List<string> SummitUnPro(string para,string Data)
        {
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            List<string> list = new List<string>();
            Newtonsoft.Json.Linq.JArray jsonArr = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(para);
            string FormDataY = jsonArr[0].ToString();
            string JsonDataY = jsonArr[1].ToString();
            Newtonsoft.Json.Linq.JArray jsonArr1 = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(FormDataY);
            Newtonsoft.Json.Linq.JArray jsonArr2 = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(JsonDataY);

            var FormData = jsonArr1[0];
            var JsonData = jsonArr2[0];
            try
            {
                string cMOLotNo = JsonData["生产批次号"].ToString();
                string PEquipment = JsonData["设备"].ToString();
                string Operator = JsonData["员工Num"].ToString();
                string GNumber = JsonData["良品数"].ToString();
                string ANumber = JsonData["不良数"].ToString();
                string IMaterialsNum = JsonData["来料数"].ToString() == "0" ? GNumber : JsonData["来料数"].ToString();
                string cProcess = JsonData["当前工序"].ToString();
               
                string YieldRate = (float.Parse(GNumber) / (float.Parse(GNumber) + float.Parse(ANumber))).ToString();
                string CreatePerson = JsonData["员工Num"].ToString();
                //查询工序ID
                string cProcessCode = "";
                string sqlcode = string.Format(@"SELECT * FROM [192.168.1.5].UFDATA_168_2013.dbo.sfc_operation where Description = '{0}';", cProcess);
                var k1 = CommonMethod.Instance.selectDatabase(sqlcode);
                var KnRow = k1.Select($"Description = '{cProcess}'");
                if (KnRow.Length > 0)
                {
                    var Kn1 = KnRow[0];
                    cProcessCode = Kn1["OperationId"].ToString();
                }
                else
                {
                    throw new Exception("查询工序code失败.");
                }

                string startTime = JsonData["开始时间"].ToString();

                if (!JsonData["开始时间"].ToString().Contains(":"))
                {
                    startTime = startTime.Insert(2, ":");
                }
                string cProStartTime = JsonData["开始日期"].ToString() + " " + startTime;
                string cProEndTime = JsonData["结束日期"].ToString() + " " + JsonData["结束时间"].ToString();

                bool timeOK = CommonMethod.Instance.DataLineOut(cProStartTime, cProEndTime);
                if(!timeOK)
                {
                    throw new Exception("开始时间大于结束时间:" + "生产批次号：" + JsonData["生产批次号"].ToString() + "，良品数：" + JsonData["良品数"].ToString() + "，工序号:" + cProcessCode);
                }

                string isReturnReport = "0";
                if (JsonData["返工报工"].ToString().Contains("是"))
                {
                    isReturnReport = "1";
                }

                string shiftName = JsonData["班次"].ToString();
                string orderNo = JsonData["生产订单号"].ToString();
                string lotType = JsonData["lotType"].ToString();
                string ReportTime = CommonMethod.Instance.getTimes1();
                string NYR = ReportTime.Split(' ')[0];
                float reportQty = float.Parse(GNumber) + float.Parse(ANumber);

                string CL = FormData["CL"].ToString() == "" ? "null" : FormData["CL"].ToString();
                string CH = FormData["CH"].ToString() == "" ? "null" : FormData["CH"].ToString();
                string DF = FormData["DF"].ToString() == "" ? "null" : FormData["DF"].ToString();
                string ESR = FormData["ESR"].ToString() == "" ? "null" : FormData["ESR"].ToString();
                string LC = FormData["LC"].ToString() == "" ? "null" : FormData["LC"].ToString();
                string Others = FormData["Others"].ToString() == "" ? "null" : FormData["Others"].ToString();
                string TaskTime = FormData["WorkTime"].ToString() == "" ? "null" : FormData["WorkTime"].ToString();
                string DelayTime = FormData["P_time"].ToString() == "" ? "null" : FormData["P_time"].ToString();
                string ServicingTime = FormData["maintenance_time"].ToString() == "" ? "null" : FormData["maintenance_time"].ToString();
                string ChangeTime = FormData["Change"].ToString() == "" ? "null" : FormData["Change"].ToString();
                string ProvingTime = FormData["jianyan"].ToString() == "" ? "null" : FormData["jianyan"].ToString();
                string OtherTime = FormData["Other_Time"].ToString() == "" ? "null" : FormData["Other_Time"].ToString();

                //string insertSql = "";
                string SQL = "";
                if(cProcessCode.Equals("1000000001") || cProcessCode.Equals("1000000022"))
                {
                    SQL += string.Format(@"update APS_ProLotOrder set cStatusNo = '0080' where cMOLotNo = '{0}'; update APS_PlanOrder set cStatusNo = '0080' where cPOrderNo = '{1}';", cMOLotNo, orderNo);
                }

                if(isReturnReport.Equals("0"))
                {
                    string querySql = string.Format(@"select a.cOrderNo,a.cMatandResNo,a.dLength,a.dWidth,a.cCateNo,b.子件损耗率,b.分母用量 from APS_ValidBOM a join View_Bom b  
    on a.cMatNo = b.成品编码 and a.cMatandResNo = b.子件物料编码 where a.cOrderNo = '{0}' and a.cOperationName = '{1}';", cMOLotNo, cProcess);

                    var kQuery = CommonMethod.Instance.selectDatabase(querySql);
                    var kQueryRow = kQuery.Select($"cOrderNo = '{cMOLotNo}'");
                    if (kQueryRow.Length > 0)
                    {
                        for(int i = 0;i <kQueryRow.Length;i++)
                        {
                            var kQRows = kQueryRow[i];
                            string cMatandResNo = kQRows["cMatandResNo"].ToString();
                            float dLength = float.Parse(kQRows["dLength"].ToString());
                            float dWidth = 0;
                            if (!kQRows["dWidth"].ToString().Equals(""))
                            {
                                dWidth = float.Parse(kQRows["dWidth"].ToString());
                            }
                            
                            string cCateNo = kQRows["cCateNo"].ToString();
                            float compScrap = float.Parse(kQRows["子件损耗率"].ToString());
                            float subQty = float.Parse(kQRows["分母用量"].ToString());
                            float matUseQty = 0;
                            if(cCateNo.Equals("Y0104") || cCateNo.Equals("Y0192") || cCateNo.Equals("Y0105"))
                            {
                                //matUseQty = (float)(float.Parse(dLength) / float.Parse(subQty) * (1 + float.Parse(compScrap) * 0.01) * float.Parse(dWidth) * 0.01 * reportQty);
                                matUseQty = (float)((dLength / subQty) * (1 + compScrap * 0.01) * dWidth * 0.001 * reportQty);
                            }
                            else
                            {
                                //matUseQty = (float)(float.Parse(dLength) / float.Parse(subQty) * (1 + float.Parse(compScrap) * 0.01) * reportQty);
                                matUseQty = (float)((dLength / subQty) * (1 + compScrap * 0.01) * reportQty);
                            }
                            SQL += string.Format(@"update APS_ValidBOM set dRealQty = {0}  where cOrderNo = '{1}' and cMatandResNo = '{2}';", matUseQty,cMOLotNo, cMatandResNo);
                        }
                    }
                }
                //插入数据到生产报工表
                //查询已开工记录
                string sqlQuery = string.Format(@"Select cMOLotNo,PEquipment,Operator,cProcess,cProStartTime,ID from APS_PhistoryTable where cMOLotNo = '{0}' and cProcess = '{1}' and cProEndTime is null", cMOLotNo, cProcess);
                var sqlQueryS = CommonMethod.Instance.selectDatabase(sqlQuery);
                var sqlQuerySRow = sqlQueryS.Select($"cMOLotNo = '{cMOLotNo}'");
                if (sqlQuerySRow.Length > 0)
                {
                    int ID = int.Parse(sqlQuerySRow[0]["ID"].ToString());
                    SQL += string.Format(@"update APS_PhistoryTable set Operator = '{0}', GNumber = '{1}',ANumber = '{2}',IMaterialsNum = '{3}',ReportTime = '{4}',NYR = '{5}',cProEndTime = '{6}'," + 
        " isReturnReport = '{7}',guid = '{8}',shiftName = '{9}' where cMOLotNo = '{10}' and cProcess = '{11}' and cProEndTime is null and ID = {12}; ", Operator, GNumber, ANumber, IMaterialsNum, ReportTime, NYR, cProEndTime,
    isReturnReport, "NULL", shiftName, cMOLotNo, cProcess,ID);
                    SQL += string.Format(@"insert into QC_DProductDetails (pid,cMOLotNo,PEquipment,cProcess,CL,CH,DF,ESR,LC,Other,TaskTime,DelayTime,ServicingTime,ChangeTime,ProvingTime,OtherTime,CreateTime) "+ 
"  values ('{0}','{1}','{2}','{3}',{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}, CONVERT ( VARCHAR ( 30 ), GETDATE(), 111 ));", ID, cMOLotNo, PEquipment, cProcess, CL, CH, DF, ESR, LC, Others, TaskTime, DelayTime, ServicingTime
, ChangeTime, ProvingTime, OtherTime);
                }
                else
                {
                    SQL += string.Format(@"insert into APS_PhistoryTable (cMOLotNo,PEquipment,Operator,GNumber,ANumber,IMaterialsNum,ReportTime,cProcess,NYR,isSyncReport,cProcessCode,cProStartTime,cProEndTime,isReturnReport,guid,shiftName)" + 
" values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','1','{9}','{10}','{11}','{12}','{13}','{14}');", cMOLotNo, PEquipment, Operator, GNumber, ANumber, IMaterialsNum, ReportTime, cProcess, NYR, cProcessCode, cProStartTime, cProEndTime, isReturnReport, "NULL", shiftName);

                    //插入数据到不良品详细表
                    SQL += string.Format(@"Declare @id int; select @id = max(ID) from APS_PhistoryTable where cMOLotNo='{0}' and cProcess='{1}' and PEquipment ='{2}'; insert into QC_DProductDetails (pid,cMOLotNo,PEquipment,cProcess,CL,CH,DF,ESR,LC,Other,TaskTime,DelayTime,ServicingTime,ChangeTime,ProvingTime,OtherTime,CreateTime)" +
" values (@id,'{3}','{4}','{5}',{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},CONVERT ( VARCHAR ( 30 ), GETDATE(), 111 ));", cMOLotNo, cProcess, PEquipment, cMOLotNo, PEquipment, cProcess, CL, CH, DF, ESR, LC, Others, TaskTime, DelayTime,
ServicingTime, ChangeTime, ProvingTime, OtherTime);

                }

                //更新工艺路径表
                SQL += string.Format(@"update APS_ValidRouting set ReportTime='{0}' where cOrderNo='{1}' and cOperationName='{2}';", ReportTime, cMOLotNo, cProcess);
                if (float.Parse(YieldRate) <= 0.8)
                {
                    SQL += string.Format(@"insert into APS_ExceptionRecord (cMOLotNo,PEquipment,AType,AClassification,EDescription,CreatePerson,CreateTime,cProcess,guid) values " +
                "('{0}','{1}','生产管理','物料异常','不良率超标','{2}',GETDATE(),'{3}','{4}');", cMOLotNo, PEquipment, CreatePerson, cProcess, "NULL");
                }
                //执行sql插入
                var connstr = SqlHelper.GetConnSting();
                SqlHelper.ExecuteNonQuery(connstr, CommandType.Text, SQL);
                list.Add("[0]");
                //CommonMethod.Instance.InsertLog(name, SQL, CommonMethod.LogType.Info, para, "不良品提交成功");
                CommonMethod.Instance.InsertLog1(JsonData["生产批次号"].ToString(), "不良品提交成功", Data, CommonMethod.LogType.Info, name, "", true);
            }
            catch(Exception e)
            {
                list.Add(e.Message);
                // CommonMethod.Instance.InsertLog(name, e.Message, CommonMethod.LogType.Error, para, "不良品提交失败");
                CommonMethod.Instance.InsertLog1(JsonData["生产批次号"].ToString(), e.Message, Data, CommonMethod.LogType.Error, name, "", true);
            }
            return list;
        }
    }
}